package com.chenwb.concurrency.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReenterLockCondition implements Runnable {

	public static ReentrantLock reenteantLock = new ReentrantLock();
	public static Condition condition = reenteantLock.newCondition();

	/**
	 * 执行
	 */
	@Override
	public void run() {
		try {
			System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + " " +
					"get lock");
			reenteantLock.lock();

			System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + " " +
					"thread wait");
			condition.await();

		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			if (reenteantLock.isHeldByCurrentThread()) {
				reenteantLock.unlock();
				System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + " " +
						"unlock");
			}
		}
	}

	/**
	 * 执行结果
	 * 1585796190 main
	 * 1585796190 thread1 get lock
	 * 1585796190 thread1 thread wait
	 * 1585796192 thread1 unlock
	 * t1线程启动，到condition.await();线程阻塞，等主线程sleep 2s后condition.signal();唤醒t1线程
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		ReenterLockCondition thread = new ReenterLockCondition();
		Thread t1 = new Thread(thread, "thread1");
		System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName());
		t1.start();
		Thread.sleep(2000);

		reenteantLock.lock(); //这里加锁的目的是为了防止并发问题
		try {
			condition.signal();
		} catch (IllegalMonitorStateException e) {
			System.out.println("解锁失败");
		}
		reenteantLock.unlock();
	}
}
